﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Columns;

namespace TaxiDispatchClient
{
    public partial class TaxiRouteStatisticsListForm : DevExpress.XtraEditors.XtraForm
    {
        
        public TaxiRouteStatisticsListForm()
        {
            InitializeComponent();
            DevExpress.Data.CurrencyDataController.DisableThreadingProblemsDetection = true;
            //dateEdit1.DateTime = DateTime.Today.AddDays(-2);
            //dateEdit2.DateTime = DateTime.Now;

            dateEdit1.DateTime = DateTime.Today.AddDays(-1);
            dateEdit2.DateTime = DateTime.Today.AddDays(-1);

            _chargeInfo = Common.OperateConfig.GetClientChargingModel();

            _dtStatistics = new DataTable();
            _dtStatistics.Columns.Add("Driver");
            _dtStatistics.Columns.Add("TaxiNo");
            _dtStatistics.Columns.Add("PhoneNumber");
            _dtStatistics.Columns.Add("Date");
            
            _dtStatistics.Columns.Add("DayDistance");//白天载客里程
            _dtStatistics.Columns.Add("DayOrderCount");//白天单数
            _dtStatistics.Columns.Add("DayCharge");//白天收费
            _dtStatistics.Columns.Add("NightDistance");//晚班里程
            _dtStatistics.Columns.Add("NightOrderCount");//晚班单数
            _dtStatistics.Columns.Add("NightCharge");//晚班收费

            _dtStatistics.Columns.Add("DayEmptyDistance");//白天空载里程
            _dtStatistics.Columns.Add("NightEmptyDistance");//夜班空载里程

            _dtStatistics.Columns.Add("TotalDistance");//总里程
            _dtStatistics.Columns.Add("TotalOrder");//总单数
            _dtStatistics.Columns.Add("TotalCharge");//总收费

            _dtStatistics.Columns.Add("TotalEmptyDistance");//总空载里程

            Thread tbind = new Thread(BindData);
            tbind.IsBackground = true;
            tbind.Start();
        }

        private DataTable _dtGroup;
        private List<string> _companylist;
        private Model.TaxiChargeInfo _chargeInfo;
        private DataTable _dtStatistics;


        private void InitControl()
        {
            DataSet ds = null;
            do
            {
                ds = MainForm.PositionService.TaxiGroupGetList("");
                Thread.Sleep(500); 
            } while (ds==null || ds.Tables.Count==0);
            _dtGroup = ds.Tables[0];

            List<string> company;
            do
            {
                company = MainForm.PositionService.GetCompanyList();
            } while (company==null);
            _companylist = company;

        }

        private void BindData()
        {

            string startTime="";
            string endTime = "";
            string phoneNumber = "";            
            int type = imageComboBoxEdit1.SelectedIndex; 
            try
            {
                if (type == 0)//所有车辆  应进行公司筛选
                {
                    startTime = dateEdit1.DateTime.ToString("yyyy-MM-dd") +
                                " 00:00:00";
                    //endTime = dateEdit1.DateTime.ToString("yyyy-MM-dd") +
                    //            " 23:59:59";
                    endTime = dateEdit2.DateTime.ToString("yyyy-MM-dd") +
                              " 23:59:59";

                    if (MainForm.MyUserInfo.CompanyName!=Service.PowerConfig.MainCompanyName)
                    {
                       endTime += "' and CompanyName='" + MainForm.MyUserInfo.CompanyName;
                    }
                }
                else if (type == 1)//单辆车
                {
                    phoneNumber = btnText_phoneNumber.Text;
                    startTime = dateEdit1.DateTime.ToString("yyyy-MM-dd") +
                                " 00:00:00";
                    endTime = dateEdit2.DateTime.ToString("yyyy-MM-dd") +
                                " 23:59:59";
                }
                DataSet ds = MainForm.PositionService.TaxiRouteGetStatisticsByPara(
                    phoneNumber, startTime, endTime);

               
                //string phoneNumber = ""; 
                //string   startTime = (
                //    dateEdit1.DateTime.ToString("yyyy-MM-dd") +" 00:00:00");
                //string  endTime = (
                //    dateEdit2.DateTime.ToString("yyyy-MM-dd") +" 23:59:59");
                //DataSet ds=null;
                //if (type==1)//单量
                //{
                //    phoneNumber = btnText_phoneNumber.Text;
                //}
                 

                if (ds!=null && ds.Tables.Count>0)
                {

                    _dtStatistics.Rows.Clear();

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        string strPhone = row["PhoneNumber"].ToString();
                        string strName = row["Name"].ToString();
                        string strTaxiNo = row["TaxiNo"].ToString();
                        string strState = row["State"].ToString();
                        DateTime dateTime = DateTime.Parse(row["StartTime"].ToString());
                        float distance = float.Parse(row["Distance"].ToString());

                        string selvalue = dateTime.ToString("MM月dd日");
                        string strWhere = "PhoneNumber ='" + strPhone 
                                          + "' and Date='" + selvalue + "'";
                        DataRow[] rows = _dtStatistics.Select(strWhere);

                        int rowlength = rows.Length;
                        if (strState=="0")  // 载客状态
                        {
                            #region 由里程 根据配置计算出收费
                            float charge = 0;
                            if (dateTime.TimeOfDay.Hours >= 6
                                && dateTime.TimeOfDay.Hours < 22)//白班
                            {
                                //未超出起步里程 为起步价
                                if (distance < _chargeInfo.DayInitDistance)
                                {
                                    charge = _chargeInfo.DayInitPrice;
                                }
                                else
                                {
                                    //刚好为起步里程时 需要加上超出的补贴  
                                    if (distance == _chargeInfo.DayInitDistance)
                                    {
                                        charge = _chargeInfo.DayInitPrice + _chargeInfo.DayOverSubsidy;
                                    }
                                    //超出起步里程时 需要加上超出补贴 且多出的每公里按 超出价格计算
                                    else
                                    {
                                        double overCharge = Math.Floor(distance - _chargeInfo.DayInitDistance +0.5)
                                                           * _chargeInfo.DayOverPrice;
                                        charge = _chargeInfo.DayInitPrice + _chargeInfo.DayOverSubsidy
                                                 + (float)overCharge;
                                        //超出空车返回补贴里程值 需另加空车返回补贴  按总价百分比计算
                                        if (distance > _chargeInfo.DayEmptyBackDistance)
                                        {
                                            charge += (charge * _chargeInfo.DayEmptyBackSubsidy) / 100;
                                        }
                                    }
                                }

                                if (rows.Length==0)
                                {
                                    DataRow newDr = _dtStatistics.NewRow();
                                    newDr["Driver"] = strName;
                                    newDr["PhoneNumber"] = strPhone;
                                    newDr["TaxiNo"] = strTaxiNo;
                                    newDr["Date"] = dateTime.ToString("MM月dd日");
                                    newDr["DayDistance"] = distance.ToString("f2");
                                    newDr["DayOrderCount"] = 1;
                                    newDr["DayCharge"] = charge.ToString("f1");
                                    newDr["NightDistance"] =0;
                                    newDr["NightOrderCount"] =0;
                                    newDr["NightCharge"] =0;
                                  
                                    newDr["DayEmptyDistance"] =0;
                                    newDr["NightEmptyDistance"] =0;
                                    newDr["TotalDistance"] =distance.ToString("f2");
                                    newDr["TotalEmptyDistance"] = 0;
                                    newDr["TotalOrder"] =1;
                                    newDr["TotalCharge"] =charge.ToString("f1");
                                    _dtStatistics.Rows.Add(newDr);
                                }
                                else
                                {                                                                     
                                    rows[0]["DayDistance"] = (float.Parse(rows[0]
                                        ["DayDistance"].ToString()) + distance).ToString("f2");
                                    
                                    rows[0]["DayOrderCount"] =int.Parse(rows[0]
                                        ["DayOrderCount"].ToString()) + 1;
                                    
                                    rows[0]["DayCharge"] = (float.Parse(rows[0]
                                        ["DayCharge"].ToString()) + charge).ToString("f1");
                                                                        
                                    rows[0]["TotalDistance"] = (float.Parse(
                                        rows[0]["TotalDistance"].ToString())+distance).ToString("f2");

                                    rows[0]["TotalOrder"] = float.Parse(
                                        rows[0]["TotalOrder"].ToString()) + 1;

                                    rows[0]["TotalCharge"] = (float.Parse(
                                        rows[0]["TotalCharge"].ToString()) + charge).ToString("f1");
                                }


                            }
                            else //夜班
                            {
                                //未超出起步里程 为起步价
                                if (distance < _chargeInfo.NightInitDistance)
                                {
                                    charge = _chargeInfo.NightInitPrice;
                                }
                                else
                                {
                                    //刚好为起步里程时 需要加上超出的补贴  
                                    if (distance == _chargeInfo.DayInitDistance)
                                    {
                                        charge = _chargeInfo.NightInitPrice + _chargeInfo.NightOverSubsidy;
                                    }
                                    //超出起步里程时 需要加上超出补贴 且多出的每公里按 超出价格计算
                                    else
                                    {
                                        double overCharge = Math.Floor(distance - _chargeInfo.NightInitDistance 
                                               + 0.5) * _chargeInfo.NightOverPrice;
                                        charge = _chargeInfo.NightInitPrice + _chargeInfo.NightOverSubsidy
                                                 + (float)overCharge;
                                        //超出空车返回补贴里程值 需另加空车返回补贴  按总价百分比计算
                                        if (distance > _chargeInfo.NightEmptyBackDistance)
                                        {
                                            charge += (charge * _chargeInfo.NightEmptyBackSubsidy)
                                                / 100;
                                        }
                                    }
                                }


                                if (rows.Length == 0)
                                {
                                    DataRow newDr = _dtStatistics.NewRow();
                                    newDr["Driver"] = strName;
                                    newDr["TaxiNo"] = strTaxiNo;
                                    newDr["PhoneNumber"] = strPhone;
                                    newDr["Date"] = dateTime.ToString("MM月dd日");
                                    newDr["DayDistance"] = 0;
                                    newDr["DayOrderCount"] = 0;
                                    newDr["DayCharge"] = 0;
                                    newDr["NightDistance"] = distance.ToString("f2");
                                    newDr["NightOrderCount"] = 1;
                                    newDr["NightCharge"] = charge.ToString("f1");

                                    newDr["DayEmptyDistance"] = 0;
                                    newDr["NightEmptyDistance"] = 0;
                                    newDr["TotalDistance"] = distance.ToString("f2");
                                    newDr["TotalEmptyDistance"] = 0;
                                    newDr["TotalOrder"] = 1;
                                    newDr["TotalCharge"] = charge;
                                    _dtStatistics.Rows.Add(newDr);
                                }
                                else
                                {
                                    rows[0]["NightDistance"] = (float.Parse(rows[0]
                                        ["NightDistance"].ToString()) + distance).ToString("f2");

                                    rows[0]["NightOrderCount"] = int.Parse(rows[0]
                                        ["NightOrderCount"].ToString()) + 1;

                                    rows[0]["NightCharge"] = (float.Parse(rows[0]
                                        ["NightCharge"].ToString()) + charge).ToString("f1");

                                    rows[0]["TotalDistance"] = (float.Parse(
                                        rows[0]["TotalDistance"].ToString()) + distance).ToString("f2");

                                    rows[0]["TotalOrder"] = float.Parse(
                                        rows[0]["TotalOrder"].ToString()) + 1;

                                    rows[0]["TotalCharge"] = (float.Parse(
                                        rows[0]["TotalCharge"].ToString()) + charge).ToString("f1");
                                }


                            }
                            #endregion

                        

                        }
                        else//空载状态
                        {
                            if (dateTime.TimeOfDay.Hours >= 6
                                && dateTime.TimeOfDay.Hours < 22) //白班 空载
                            {
                                
                                if (rows.Length == 0)
                                {
                                    DataRow newDr = _dtStatistics.NewRow();
                                    newDr["Driver"] = strName;
                                    newDr["TaxiNo"] = strTaxiNo;
                                    newDr["PhoneNumber"] = strPhone;
                                    newDr["Date"] = dateTime.ToString("MM月dd日");
                                    newDr["DayDistance"] = 0;
                                    newDr["DayOrderCount"] = 0;
                                    newDr["DayCharge"] = 0;
                                    newDr["NightDistance"] = 0;
                                    newDr["NightOrderCount"] = 0;
                                    newDr["NightCharge"] = 0;

                                    newDr["DayEmptyDistance"] = distance.ToString("f2");
                                    newDr["NightEmptyDistance"] = 0;
                                    newDr["TotalDistance"] = 0;
                                    newDr["TotalEmptyDistance"] = distance.ToString("f2");
                                    newDr["TotalOrder"] = 0;
                                    newDr["TotalCharge"] = 0;
                                    _dtStatistics.Rows.Add(newDr);
                                }
                                else
                                {
                                    rows[0]["DayEmptyDistance"] = 
                                    (float.Parse(rows[0]["DayEmptyDistance"].ToString())+distance).ToString("f2");
                                    rows[0]["TotalEmptyDistance"] = 
                                    (float.Parse(rows[0]["TotalEmptyDistance"].ToString())+distance).ToString("f2");
                                }
                            }
                            else //夜班空载
                            {
                                
                                if (rows.Length == 0)
                                {
                                    DataRow newDr = _dtStatistics.NewRow();
                                    newDr["Driver"] = strName;
                                    newDr["TaxiNo"] = strTaxiNo;
                                    newDr["PhoneNumber"] = strPhone;
                                    newDr["Date"] = dateTime.ToString("MM月dd日");
                                    newDr["DayDistance"] = 0;
                                    newDr["DayOrderCount"] = 0;
                                    newDr["DayCharge"] = 0;
                                    newDr["NightDistance"] = 0;
                                    newDr["NightOrderCount"] = 0;
                                    newDr["NightCharge"] = 0;

                                    newDr["DayEmptyDistance"] = 0;
                                    newDr["NightEmptyDistance"] = distance.ToString("f2");
                                    newDr["TotalDistance"] = 0;
                                    newDr["TotalEmptyDistance"] = distance.ToString("f2");
                                    newDr["TotalOrder"] = 0;
                                    newDr["TotalCharge"] = 0;
                                    _dtStatistics.Rows.Add(newDr);
                                }
                                else
                                {
                                    rows[0]["NightEmptyDistance"] =
                                    (float.Parse(rows[0]["NightEmptyDistance"].ToString()) + distance).ToString("f2");  
                                    rows[0]["TotalEmptyDistance"] =
                                    (float.Parse(rows[0]["TotalEmptyDistance"].ToString()) + distance).ToString("f2");
                                }
                            }
                        }
                       
                    }
                    DataTable dtt = _dtStatistics.Copy();
                    BeginInvoke(new MethodInvoker(() =>
                        {
                            //gridControl1.DataSource = ds.Tables[0];
                            gridControl1.DataSource = dtt;
                            gridView1.GroupPanelText = "统计结果";
                            btn_select.Enabled = true;
                        }));                        
                }                
            }
            catch (Exception ex)
            {
                            
                btn_select.Enabled = true;
                if (!ex.Message.Contains("创建窗口句柄之前"))
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);    
                }
                
            }
        }



        private void imageComboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (imageComboBoxEdit1.SelectedIndex)
            {
                case 0:                  
                    btnText_phoneNumber.Visible = false;
                    //label_to.Visible = false;
                    //dateEdit2.Visible = false;
                    //dateEdit1.DateTime = DateTime.Now;
                    break;
                case 1:
               
                    btnText_phoneNumber.Visible = true;
                    btnText_phoneNumber.Text = "";
                    //label_to.Visible = true;
                    //dateEdit2.Visible = true;
                    //dateEdit1.DateTime = DateTime.Now.AddDays(-10);
                    break;               
            }
        }

        private void btn_select_Click(object sender, EventArgs e)
        {
            btn_select.Enabled = false;
            if (!CheckPass())
            {                 
                btn_select.Enabled = true;                 
                return;
            }
            gridView1.GroupPanelText = "数据查询中...";
            Thread t = new Thread(BindData);
            t.IsBackground = true;
            t.Start();
        }


        private void btn_exportToExcel_MouseClick(object sender, MouseEventArgs e)
        {

            saveFileDialog1.FileName = "车辆行驶里程统计";
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView1.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");
            }
        }

        private bool CheckPass()
        {
            switch (imageComboBoxEdit1.SelectedIndex)
            {
                case 1:
                    if (btnText_phoneNumber.Text.Trim() == "")
                    {
                        XtraMessageBox.Show("请输入要查询的车辆的手机号码！");
                        btnText_phoneNumber.Focus();
                        return false;
                    }
                    break;
             
            }
            return true;
        }


        #region 窗体控件效果
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void PhoneUserForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
        #endregion

        private void btnText_phoneNumber_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            DriverInfoForm form = new DriverInfoForm();
            form.ShowDialog();
            DataRow row = form.gridView1.GetDataRow(form.gridView1.FocusedRowHandle);
            if (row != null)
            {
                btnText_phoneNumber.Text = row["PhoneNumber"].ToString();                
            }
        }

       
        private void btn_report_Click(object sender, EventArgs e)
        {
            TaxiRouteStatisticsReportForm form = new TaxiRouteStatisticsReportForm();
            form.ShowDialog();
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            if (row!=null)
            {
                DateTime start = dateEdit1.DateTime;
                DateTime end = dateEdit2.DateTime;
                string phone = row["PhoneNumber"].ToString();
                TaxiRouteHistoryForm form = new TaxiRouteHistoryForm(start, end, phone);
                form.ShowDialog();
            }
        }
         
    }
}